﻿using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.DBFactory.Database;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace QYmall.Core.Services
{
    /// <summary>
    /// 商品类别接口实现
    /// </summary>
    public class ShopCategoryService : BaseService, IShopCategoryService
    {
        public ShopCategoryService(IDbContextFactory contentFactory) : base(contentFactory) { }

        /// <summary>
        /// 根据父ID返回一级列表
        /// </summary>
        public async Task<IEnumerable<ShopCategory>> QueryListAsync(int top, int parentId, int status, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = _context.Set<ShopCategory>().Where(x => x.ParentId == parentId && (status == -1 || x.Status == status)).OrderByBatch("SortId,Id");
            if (top > 0) result = result.Take(top);//等于0显示所有数据
            return await result.ToListAsync();
        }

        /// <summary>
        /// 根据租户ID与父ID返回一级列表
        /// </summary>
        public async Task<IEnumerable<ShopCategory>> QueryListMerchantIdAsync(int merchantId, int top, int parentId, int status, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = _context.Set<ShopCategory>().Where(x => x.MerchantId == merchantId && x.ParentId == parentId && (status == -1 || x.Status == status)).OrderByBatch("SortId,Id");
            if (top > 0) result = result.Take(top);//等于0显示所有数据
            return await result.ToListAsync();
        }


        /// <summary>
        /// 根据父ID返回一级列表(带商品)
        /// </summary>
        public async Task<IEnumerable<ShopCategoryGoodsClientDto>> QueryGoodsListAsync(int categoryTop, int goodsTop, int status,
                Expression<Func<ShopGoods, bool>> funcWhere, string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //构造查询表达式
            var query = _context.Set<ShopCategory>()
                .Where(x => x.ParentId == 0 && (status == -1 || x.Status == status))
                .OrderByBatch(orderBy)
                .Take(categoryTop)
                .Select(c => new
                {
                    Category = c,
                    ShopGoods = _context.Set<ShopGoods>()
                        .Include(x => x.CategoryRelations)
                        .Where(x => x.CategoryRelations.Any(r => r.CategoryId == c.Id))
                        .Where(funcWhere)
                        .OrderBy(x => x.SortId)
                        .ThenByDescending(x => x.Id)
                        .Take(goodsTop)
                        .ToList()
                })
                .Select(cg => new ShopCategoryGoodsClientDto
                {
                    Id = cg.Category.Id,
                    Title = cg.Category.Title,
                    ImgUrl = cg.Category.ImgUrl,
                    GoodsList = cg.ShopGoods.Select(x => new ShopGoodsClientDto
                    {
                        Id = x.Id,
                        Title = x.Title,
                        Zhaiyao = x.Zhaiyao,
                        ImgUrl = x.ImgUrl,
                        MarketPrice = x.MarketPrice,
                        SellPrice = x.SellPrice
                    })
                });

            return await query.ToListAsync();
        }

        /// <summary>
        /// 根据父ID返回目录树
        /// </summary>
        public async Task<IEnumerable<ShopCategoryDto>> QueryListAsync(int parentId, int status, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var listData = await _context.Set<ShopCategory>().ToListAsync();
            //调用递归重新生成目录树
            List<ShopCategoryDto> result = await GetChilds(listData, parentId, status);
            return result;
        }

        /// <summary>
        /// 根据租户ID与父ID返回目录树
        /// </summary>
        public async Task<IEnumerable<ShopCategoryDto>> QueryListByMerchantIdAsync(int merchantId, int parentId, int status, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var listData = await _context.Set<ShopCategory>().Where(x => x.MerchantId == merchantId).ToListAsync();
            //调用递归重新生成目录树
            List<ShopCategoryDto> result = await GetChilds(listData, parentId, status);
            return result;
        }

        /// <summary>
        /// 根据条件删除数据(迭代删除)
        /// </summary>
        public async Task<bool> DeleteAsync(Expression<Func<ShopCategory, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var listData = await _context.Set<ShopCategory>().ToListAsync();//查询所有数据
            var list = await _context.Set<ShopCategory>().Where(funcWhere).ToListAsync();
            if (list == null)
            {
                return false;
            }
            foreach (var modelt in list)
            {
                await DeleteChilds(listData, modelt.Id);//删除子节点
                _context.RemoveRange(modelt);//删除当前节点
            }
            return await this.SaveAsync();
        }

        #region 辅助私有方法
        /// <summary>
        /// 迭代循环删除
        /// </summary>
        private async Task DeleteChilds(IEnumerable<ShopCategory> listData, int parentId)
        {
            if (_context == null)
            {
                throw new ResponseException("请选连接到数据库");
            }
            IEnumerable<ShopCategory> models = listData.Where(x => x.ParentId == parentId);
            foreach (var modelt in models)
            {
                await DeleteChilds(listData, modelt.Id);//迭代
                _context.RemoveRange(modelt);
            }
        }

        /// <summary>
        /// 迭代循环返回目录树(私有方法)
        /// </summary>
        private async Task<List<ShopCategoryDto>> GetChilds(IEnumerable<ShopCategory> listData, int parentId, int status)
        {
            List<ShopCategoryDto> listDto = new();
            IEnumerable<ShopCategory> models = listData.Where(x => x.ParentId == parentId && (status == -1 || x.Status == status)).OrderByBatch("SortId");//查找并排序
            foreach (ShopCategory modelt in models)
            {
                ShopCategoryDto modelDto = new ShopCategoryDto
                {
                    Id = modelt.Id,
                    ParentId = modelt.ParentId,
                    Title = modelt.Title,
                    ImgUrl = modelt.ImgUrl,
                    Content = modelt.Content,
                    SortId = modelt.SortId,
                    Status = modelt.Status,
                    AddBy = modelt.AddBy,
                    AddTime = modelt.AddTime,
                    UpdateBy = modelt.UpdateBy,
                    UpdateTime = modelt.UpdateTime,
                    MerchantId = modelt.MerchantId
                };
                modelDto.Children.AddRange(
                    await GetChilds(listData, modelt.Id, status)
                );
                listDto.Add(modelDto);
            }
            return listDto;
        }
        #endregion
    }
}
